<template>
  <lay-container fluid="true" class="organization-box">

    <div class="table-box">
      <lay-table id="unitId" :height="`100%`" :columns="columns" :loading="loading" children-column-name="children"
        :data-source="unitDataSource" :default-toolbar="true" :default-expand-all="defaultExpandAll" :expand-index="1">
        <template #toolbar>
          <lay-button size="sm" @click="changeVisibleUnit('新建', null, 0)" type="normal">
            新建
          </lay-button>
          <lay-button size="sm" @click="expandAll(true)">展开全部</lay-button>
          <lay-button size="sm" @click="expandAll(false)">折叠全部</lay-button>
        </template>
        <template #option="{ row }">
          <lay-button @click="changeVisibleUnit('新建', null, row.unitId)" size="xs" border="blue" > 添加
          </lay-button>
          <lay-button @click="changeVisibleUnit('修改', row, row.parentId)" size="xs" border="green"> 修改
          </lay-button>
          <lay-button v-if="!row.children" @click="toRemove(row)" size="xs" border="red" border-style="dashed"> 删除
          </lay-button>
        </template>
        <template #uru="{ row }">
          <lay-button @click="changeVisibleUnitRoleUser('指派用户', row.unitId)"
            size="xs" border="blue" > 指派
          </lay-button>
        </template>
        <template #status="{ row }">
          <lay-switch :model-value="row.status == 1" @change="changeStatus($event, row)"></lay-switch>
        </template>
      </lay-table>
    </div>
    
    <lay-layer v-model="visibleUnit" :title="title" :area="['700px', '370px']">
      <div style="padding: 20px">
        <lay-form :model="formData" required>
          <lay-row>
            <lay-col md="12">
              <lay-form-item label="名称" prop="unitName">
                <lay-input v-model="formData.unitName"></lay-input>
              </lay-form-item>
              <lay-form-item label="Logo" prop="unitLogo">
                <lay-input v-model="formData.unitLogo"></lay-input>
              </lay-form-item>
              <lay-form-item label="检索代码" prop="unitCode">
                <lay-input v-model="formData.unitCode"></lay-input>
              </lay-form-item>
              <lay-form-item label="数据代码" prop="unitDbCode">
                <lay-input v-model="formData.unitDbCode"></lay-input>
              </lay-form-item>
            </lay-col>
            <lay-col md="12">
              <lay-form-item label="排序" prop="sort">
                <lay-input-number v-model="formData.sort" style="width: 100%" position="right"></lay-input-number>
              </lay-form-item>
              <lay-form-item label="父级编号" prop="parentId">
                <lay-input v-model="formData.parentId"></lay-input>
              </lay-form-item>
            </lay-col>
          </lay-row>
        </lay-form>
        <div style="width: 97%; text-align: right">
          <lay-button size="sm" type="primary" @click="toSubmit">保存</lay-button>
          <lay-button size="sm" @click="toCancel">取消</lay-button>
        </div>
      </div>
    </lay-layer>
    
    <lay-layer type="drawer" :title="false" :closeBtn="false" v-model="visibleURU">
      <div style="padding: 20px">
      <lay-form :model="unitURData" ref="urulayFormRef" label-width="60" size="sm">
        <lay-form-item label="角色" prop="roleId" required>
          <lay-select v-model="unitURData.roleId" :show-search="true"
            :options="rolesData"> </lay-select>
        </lay-form-item>
        <lay-form-item label="用户" prop="userId" required >
          <lay-select v-model="unitURData.userId" :show-search="true"
            :options="usersData"> </lay-select>
        </lay-form-item>
        <lay-form-item style="text-align: right">
          <lay-button type="primary" @click="toUruSubmit">提交</lay-button>
        </lay-form-item>
      </lay-form>
      </div>
    </lay-layer>

  </lay-container>
</template>

<script setup lang="ts">
  import { ref, reactive } from 'vue'
  import { layer } from '@layui/layui-vue'
  
  import { unitTree, unitAdd, unitRemove, unitRoles, unitUsers, unitUserRoleAdd } 
    from '../../../api/module/system';
  
  // 其他
  // -- 加载中
  const loading = ref(false);
  const title = ref('新增');
  const titleURU = ref('');
  const defaultExpandAll = ref(true);
  // -- 是否可见
  const visibleUnit = ref(false);
  const visibleURU = ref(false);
  // -- 数据源
  const unitDataSource = ref([]);
  const rolesData = ref([]);
  const usersData = ref([]);
  // -- 表结构
  const columns = ref([
    { title: "复选", type: "checkbox" },
    
    { title: '名称', key: 'unitName' },
    { title: '编号', key: 'unitId', hide: true },
    { title: '父编号', key: 'parentId', hide: true },
    { title: '代码', key: 'unitCode' },
    { title: 'Logo url', key: 'unitLogo' }, 
    { title: '数据代码', key: 'unitDbCode' }, 
    
    { title: '排序', key: 'sort', hide: false },
    { title: '启用', width: '80px', key: 'status', customSlot: 'status' }, 
     
    { title: '指派', width: '60px', customSlot: 'uru' },
    { title: '操作', width: '160px', customSlot: 'option', fixed: 'right' }
  ]);
  // --
  // 表单
  // -- 表单数据
  const formData = ref({"unitName": "", "unitLogo": "", "unitCode": "", "unitDbCode": "", "sort": 99, "parentId": 0, "status": 1});
  const unitURData = ref({"unitId": null,"roleId": null,"userId": null});
  // -- 表单标签
  const urulayFormRef = ref();
  
  // 
  function loadDataSource(){
    unitTree().then(({ data, code, msg }) => {
      if (code == 200) {
        unitDataSource.value = data;
      }
      loading.value = false;
    })
  }
  function loadUserRoles(){
    unitRoles().then(({ data, code, msg }) => {
      if (code == 200) {
        rolesData.value = data;
      }
      loading.value = false;
    })
    unitUsers().then(({ data, code, msg }) => {
      if (code == 200) {
        usersData.value = data;
      }
      loading.value = false;
    })
  }
  // 删除
  function toRemove(row: any) {
    layer.confirm('您将删除 ['+row.unitName+']，相关指派将被解除。', {
      title: '提示',
      btn: [
        {
          text: '确定',
          callback: (id : any) => {
            unitRemove({id: row.unitId}).then(({ code, msg }) => {
              if (code == 200) {
                layer.msg('成功删除！', { icon: 1, time: 1000 });
                loadDataSource();
              } else {
                layer.msg(msg, { icon: 2, time: 1000 })
              }
            })
            layer.close(id)
          }
        },
        {
          text: '取消',
          callback: (id : any) => {
            layer.msg('您已取消操作')
            layer.close(id)
          }
        }
      ]
    })
  }
  // 提交
  function toSubmit() {
    unitAdd(formData.value).then(({ code, msg, message }) => {
      if (code == 200) {
        layer.msg('保存成功！', { icon: 1, time: 1000 });
      } else {
        layer.msg(message? message:msg, { icon: 2, time: 1000 })
      }
      loadDataSource();
      visibleUnit.value = false
    })
  }
  function toUruSubmit(){
    urulayFormRef.value.validate(
      (isValidate : boolean, model : any, errors : any) => {
        console.log(model)
        if(isValidate){
          unitUserRoleAdd(unitURData.value).then(({ code, msg, message }) => {
            if (code == 200) {
              layer.msg('保存成功！', { icon: 1, time: 1000 });
              toCancel();
            } else {
              layer.msg(message? message:msg, { icon: 2, time: 1000 })
            }
            visibleUnit.value = false
          })
        }
        
      }
    )
  }
  function toCancel() {
    visibleUnit.value = false;
    visibleURU.value = false;
  }
  //
  function changeVisibleUnit(text : any, row : any, parentId: number) {
    title.value = text;
    if (row != null) {
      let info = JSON.parse(JSON.stringify(row))
      formData.value = info
    } else {
      formData.value = {"unitName": "", "unitLogo": "", "unitCode": "", "unitDbCode": "", "sort": 99, "parentId": parentId, "status": 1}
    }
    visibleUnit.value = !visibleUnit.value
  }
  function changeVisibleUnitRoleUser(text : any, unitId: number){
    titleURU.value = text;
    
    unitURData.value.unitId = unitId;
    
    visibleURU.value = !visibleURU.value;
  }
  //
  function changeStatus(isChecked : boolean, row : any){
    row.status = isChecked? 1 : 0;
    unitAdd(row).then(({code}) => {if(code == 200){layer.msg('修改成功');loadDataSource();}});
  }
  //
  function expandAll(flag : any) {
    defaultExpandAll.value = flag
  }
  function handleClick(node: any) {
    delete node.children;
    // selectedNode.value = node;
    // 
    // 加载 单位下的用户
    console.log(node)
  }
  const change = () => {
    loading.value = true
    
  }
  
  // --预执行
  loadDataSource();
  loadUserRoles();
</script>

<style scoped>
  .organization-box {
    height: calc(100vh - 110px); 
    margin-top: 10px; box-sizing: border-box; 
  }
  
  .top-search { margin-top: 10px; padding: 10px; height: 40px; border-radius: 4px; background-color: #fff; } 
  .table-box { margin-top: 0px; padding: 10px; height: 100%; border-radius: 4px; box-sizing: border-box; background-color: #fff; } 

  .left-tree { display: inline-block; padding: 20px 15px 0 5px; height: 1200px; border-right: 1px solid #e6e6e6; box-sizing: border-box; position: relative; }
  
  /* todo layui-tree-entry 设置无效 */ 
  .layui-tree-entry { position: relative; padding: 10px 0; height: 20px; line-height: 20px; white-space: nowrap; } 

  .isFold { position: absolute; top: 36%; right: -10px; width: 26px; height: 26px; line-height: 26px; border-radius: 13px; background-color: #fff; border: 1px solid #e6e6e6; cursor: pointer; }
  
  .search-input { display: inline-block; width: 98%; margin-right: 10px; }
  
  .isChecked { display: inline-block; background-color: #e8f1ff; color: red; }
</style>